package com.xc58.highreactor.seril;

import static com.xc58.highreactor.util.ByteUtil.getByteFormInt;
import static com.xc58.highreactor.util.ByteUtil.toInt;

import java.io.InputStream;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.ArrayList;
@SuppressWarnings({"rawtypes"})
public class ArrayListSerializer implements ISerializer<ArrayList> {
	private static final ArraySerializer ARRAY = new ArraySerializer();
	private static Field field = null;
	private static Field flen = null;
	
	public static void init() throws Exception{
		field = ArrayList.class.getDeclaredField("elementData");
		field.setAccessible(true);
		flen= ArrayList.class.getDeclaredField("size");
		flen.setAccessible(true);
	}
	
	public byte[] serialize(ArrayList rawObject) throws Exception {
		int length = flen.getInt(rawObject);
		byte[] realLength = getByteFormInt(length);
		Object[] arrays = (Object[]) field.get(rawObject);
		byte[] result = ARRAY.serialize(arrays,length);
		int clazzLength = toInt(new byte[]{result[0],result[1],result[2],result[3]});
		result[clazzLength + 4] = realLength[0];
		result[clazzLength + 5] = realLength[1];
		result[clazzLength + 6] = realLength[2];
		result[clazzLength + 7] = realLength[3];
		return result;
	}

	public ArrayList deserialize(InputStream input) throws Exception {
		ArrayList list = new ArrayList();
		Object arrays = ARRAY.deserialize(input);
		field.set(list, arrays);
		flen.set(list, Array.getLength(arrays));
		return list;
	}

}
